const roleDao = require('../dao/roleDao')
const jwt = require('jsonwebtoken')
const config = require('../config/config.js')

// 添加角色
exports.create = async ctx => {
  let body = ctx.request.body
  const res = await roleDao.create(body);
  if(res){
    ctx.body = {
      code: 0,
      message: '添加成功'
    }
  }
}

// 修改角色信息
exports.edit = async ctx => {
  let body = ctx.request.body
  console.log(body)
  const res = await roleDao.edit(body);
  if(res){
    ctx.body = {
      code: 0,
      msg:'修改成功'
    }
  }
}

// 获取所有角色(分页)
exports.getAllRole = async ctx => {
  let { p = 1,limit = 10 } = ctx.request.query
  let offset = (p - 1) * limit;
  console.log(p,limit,offset)
  let body = {
    offset:offset,
    limit:Number(limit)
  }
  const res = await roleDao.getAllRole(body);
  ctx.body = {
    code: 0,
    data: res
  }
}

// 获取某角色所有权限
exports.getRoleRules = async ctx => {
  let query = ctx.request.query
  
}

// 给角色分配权限
exports.setRules = async ctx => {

}

// 给角色分配权限
exports.setRules2 = async ctx => {
  let body = ctx.request.body
  // 删除现有权限
  await roleDao.delRules(body)
  let {
    rid,
    pid
  } = body
  pidList = pid.split(",")
  let res
  for (let i = 0; i < pidList.length; i++) {
    res = await roleDao.setRules({
      rid: rid,
      pid: pidList[i]
    });
  }
  if(res){
    ctx.body = {
      code:0,
      message:'设置成功'
    }
  }
}

// 获取某角色的所有权限
exports.getRules = async ctx => {
  let query = ctx.request.query
  const res = await roleDao.getRules(query)
  let map = []
  res.map(item => {
    map.push(item.pid)
  })
  ctx.body = {
    code:0,
    data:map
  }
}

// 给账号分配角色
exports.setRole = async ctx => {
  let body = ctx.request.body
  const res = await roleDao.setRole(body)
  ctx.body = {
    code:0,
    message:'分配成功'
  }
}